/**
 * Created by ren on 28/03/2017.
 */
'use strict';
import React, {Component} from 'react';
import {StatusBar, Navigator, AsyncStorage, Platform, BackAndroid, ToastAndroid} from 'react-native'
import {Provider} from 'react-redux';
import configureStore from './src/store'
const store = configureStore()
import Home from './src/views/Home'
import PageUtil from './src/utils/PageUtil';
import Storage from 'react-native-storage';
var storage = new Storage({
  // maximum capacity, default 1000
  size: 1000,

  // Use AsyncStorage for RN, or window.localStorage for web.
  // If not set, data would be lost after reload.
  storageBackend: AsyncStorage,

  // expire time, default 1 day(1000 * 3600 * 24 milliseconds).
  // can be null, which means never expire.
  defaultExpires: 1000 * 3600 * 24,

  // cache data in the memory. default is true.
  enableCache: true,

  // if data was not found in storage or expired,
  // the corresponding sync method will be invoked and return
  // the latest data.
  sync: {
    // we'll talk about the details later.
  }
})

let backNum = 0
class App extends Component {
  constructor(props) {
    super(props);
    // 初始化工具类
    this.pageUtil = new PageUtil();
  }

  renderScene = (route, navigator) => {
    // 工具类中的Navigator的push方法最终会将我们传入的route对象传到这里
    // 直接使用传过来的route中的内容进行页面跳转
    if (route.component) {
      return <route.component {...route.params}/>
    }
  };

  componentWillMount() {
    global.storage = storage;
    console.disableYellowBox = true;
    if (Platform.OS === 'android') {
      BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  componentWillUnmount() {
    if (Platform.OS === 'android') {
      BackAndroid.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  onBackAndroid = () => {
    const routers = this.pageUtil.getRouters();
    if (routers.length > 1) {
      this.pageUtil.pop();
      return true;
    }
    if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
      //最近2秒内按过back键，可以退出应用。
      return false;

    }

    this.lastBackPressed = Date.now();
    ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
    return true
  };

  render() {
    return (
      <Provider store={store}>
        <Navigator
          // 这里很重要，使用ref参数获取Navigator实例的引用并set到工具类中
          // 在setNavigator之前，是无法使用工具类进行页面跳转的
          ref={(navi) => {
                        this.pageUtil.setNavigator(navi);
                    }}
          initialRoute={{
                        component: Home,
                    }}
          style={{backgroundColor:'#f4f4f4'}}
          renderScene={this.renderScene}
        />
      </Provider>
    )
  }
}
export default App;